﻿// Copyright (c) ZhangPeihang. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using LaserMark.Models;
using Microsoft.Win32;
using LaserMark.View.Services;
using System.IO;
using System.IO.Compression;

namespace LaserMark.Extensions;
public static class ResolveFileExtension
{
    public static OriginalInfo Resolve(OpenFileDialog dialog, MarkOption option)
    {
        FileInfo info = new FileInfo(dialog.FileName);
        OriginalInfo original = new OriginalInfo();
        if (info.Extension == ".g")
        {
            original.Originals.Add(GCode.Read(dialog.FileName, option.GCodeOrder));
            original.FileName = dialog.SafeFileName;
            original.OriginalCount = 1;
        }
        else if (info.Extension == ".OPT" || info.Extension == ".opt")
        {
            original = ConvertOriginalInfo.Convert(dialog.FileName);
            original.FileName = dialog.SafeFileName;
        }
        else if (info.Extension == ".zip")
        {
            var temp = $"{AppContext.BaseDirectory}GTemp";
            if (Directory.Exists(temp))
            {
                Directory.Delete(temp, true);
            }
            ZipFile.ExtractToDirectory(dialog.FileName, temp);

            var files = Directory.EnumerateFiles(temp, "*.g", SearchOption.AllDirectories);
            original.FileName = dialog.SafeFileName;
            foreach (var item in files)
            {
                original.Originals.Add(GCode.Read(item, option.GCodeOrder));
            }
            original.OriginalCount = files.Count();

            Directory.Delete(temp, true);
        }

        return original;
    }
}
